#ifndef __DICTIONARY_HPP__
#define __DICTIONARY_HPP__

#include <iostream>
#include <functional>

#include <unordered_map>
#include <fstream>

#include "Log.hpp"
#include "Common.hpp"

// config default Dictionary.txt path info
const static std::string g_path = "./";
const static std::string g_filename = "dict.txt";

const static std::string g_delimiter = ": ";

using namespace LogModule;

class Dictionary
{
private:
    void PrintDict()
    {
        // LOG(LogLevel::DEBUG) << "enter PrintDict";
        for(auto & e:_dict){
            std::cout << e.first << ": " << e.second << std::endl;
        }
    }
    bool LoadDict()
    {
        std::string file = _path + _filename;
        std::ifstream in(file.c_str());
        if(!in.is_open())
        {
            LOG(LogLevel::ERROR) << "open file: "<< _filename << " error";
            return false;
        }

        std::string line;
        // std::cout << line << std::endl; 
        while(std::getline(in, line))
        {
            std::string key;
            std::string value;

            if(SplitLine(line, &key, &value, g_delimiter))
            {
                _dict.insert(std::make_pair(key,value));
            }
        }

        // 关闭流
        in.close();
        return true;
    }

public:
    Dictionary(const std::string &path = g_path, const std::string &filename = g_filename)
        : _path(path)
        , _filename(filename)
    {
        // PrintDict();
        
        if(!LoadDict())
        {
            LOG(LogLevel::ERROR) << "Load dict Err";
            return;
        }
        // PrintDict();

    }

    std::string Translate(const std::string word)
    {

        auto iter = _dict.find(word);
        // PrintDict();
        if(iter == _dict.end()){
            return "invalid word in Word-Lib";
        }
        return iter->second;
    }

    ~Dictionary(){}
private:
    std::unordered_map<std::string, std::string> _dict;
    std::string _path;
    std::string _filename;
};

#endif
